package com.glory.hikvisionmobile.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.base.Constant;
import com.glory.hikvisionmobile.bean.TrackIn.ItemWorkBean;
import com.glory.hikvisionmobile.bean.from.LocationBean;
import com.glory.hikvisionmobile.bean.from.LocationListBean;
import com.glory.hikvisionmobile.bean.from.ReplaceRecordBean;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.utils.DialogUtils;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class From_ReplaceRecordActivity extends BaseActivity {

    @BindView(R.id.tvTime)
    TextView tvTime;
    @BindView(R.id.tvRegion)
    TextView tvRegion;
    @BindView(R.id.ivRegionListArrow)
    ImageView ivRegionListArrow;
    @BindView(R.id.flRegionList)
    FrameLayout flRegionList;
    @BindView(R.id.tvSpareName)
    TextView tvSpareName;
    @BindView(R.id.ivSpareNameListArrow)
    ImageView ivSpareNameListArrow;
    @BindView(R.id.flSpareNameList)
    FrameLayout flSpareNameList;
    @BindView(R.id.tvReason)
    TextView tvReason;
    @BindView(R.id.ivReasonListArrow)
    ImageView ivReasonListArrow;
    @BindView(R.id.flReasonList)
    FrameLayout flReasonList;
    @BindView(R.id.etRemarks)
    FreeUI_ClearEditText etRemarks;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvReplay)
    TextView tvReplay;
    @BindView(R.id.tvEqp)
    TextView tvEqp;
    @BindView(R.id.ivEqpListArrow)
    ImageView ivEqpListArrow;
    @BindView(R.id.flEqpList)
    FrameLayout flEqpList;

    private List<String> locationList = new ArrayList();
    private List<String> reasonList = new ArrayList<>();
    private FreeUI_GeneralPop locationPop;
    private FreeUI_GeneralPop EqpPop;
    private FreeUI_GeneralPop reasonPop;
    private FreeUI_GeneralPop subEqpPop;
    private String location;
    private boolean isFirst = false;
    private List<String> subEquipmentId = new ArrayList<>();
    private ReplaceRecordBean replaceRecordBean;
    private List<String> subEquipmentId1 = new ArrayList<>();

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_from_replace_record;
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        replaceRecordBean = (ReplaceRecordBean) bundle.getSerializable("ReplaceRecordBean");
        if (replaceRecordBean != null) {
            tvReplay.setVisibility(View.GONE);
            tvTime.setText(replaceRecordBean.getCreated());
            tvRegion.setText(replaceRecordBean.getArea());
            flRegionList.setEnabled(false);
            tvEqp.setText(replaceRecordBean.getEqpId());
            flEqpList.setEnabled(false);
            tvSpareName.setText(replaceRecordBean.getPartName());
            flSpareNameList.setEnabled(false);
            tvReason.setText(replaceRecordBean.getReason());
            flReasonList.setEnabled(false);
            etRemarks.setText(replaceRecordBean.getComment());
            etRemarks.setEnabled(false);
        } else {
            try {
                tvTime.setText(FreeApi_DateUtils.longToString(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }


    }

    @Override
    protected void initData() {
        NetUtils.requestDara("HIK.PdaBaseLocation", this, null, new FreeUI_DialogEntityCallBack<BaseResponseBean<LocationListBean>>
                (new TypeToken<BaseResponseBean<LocationListBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LocationListBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    locationList.clear();
                    List<LocationBean> locationBeans = response.body().getBody().getxPdaLocations();
                    for (LocationBean bean : locationBeans) {
                        locationList.add(bean.getName() + "/" + bean.getDescription());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<LocationListBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaBaseLocation");
            }
        });

        NetUtils.getSelectorList("YSPJReasons", "USER", this, getSupportFragmentManager(), new NetUtils.SelectorCallback() {
            @Override
            public void onSuccess(List<String> list) {
                reasonList = list;
            }

            @Override
            public void onFail(Throwable e, String messageName) {
                loadError(e, messageName);
            }
        });
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("易损件更换记录");
        freeUI_titleView.setRightListener("取消", v -> {
            if (replaceRecordBean != null){
                return;
            }

            initPermission("Refresh", this, new ActionControlListener() {
                @Override
                public void onControlChangeListener() {
                    location = "";
                    tvRegion.setText("");
                    etRemarks.setText("");
                    tvReason.setText("");
                    tvSpareName.setText("");
                    tvEqp.setText("");
                    isFirst = false;
                    initData();
                }
            });
        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    @OnClick({R.id.flRegionList, R.id.flSpareNameList, R.id.flReasonList, R.id.tvReplay,R.id.flEqpList})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flRegionList:
                if (locationList.size() <= 0) {
                    showToast("未获取到区域列表", false);
                    return;
                }

                if (locationPop != null) {
                    if (locationPop.isShowing()) {
                        locationPop.dismiss();
                    }
                } else {
                    locationPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flRegionList.getWidth(), locationList, ivRegionListArrow, (code, i) -> {
                        tvRegion.setText(code);
                        location = code.split("/")[0];
                        tvEqp.setText("");
                        requestSubEqpList(location);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivRegionListArrow);
                locationPop.showAsDropDown(flRegionList, 0, 0);
                break;
            case R.id.flSpareNameList:
                if (tvEqp.getText().toString().trim().length() <= 0){
                    showToast("请选择机台", false);
                    return;
                }
                if (subEquipmentId1. size() <= 0){
                    showToast("未获取到备件名称列表", false);
                    return;
                }

                if (subEqpPop != null) {
                    if (subEqpPop.isShowing()) {
                        subEqpPop.dismiss();
                    }
                } else {
                    subEqpPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flSpareNameList.getWidth(), subEquipmentId1, ivSpareNameListArrow, (code, i) -> {
                        tvSpareName.setText(code);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivSpareNameListArrow);
                subEqpPop.showAsDropDown(flSpareNameList, 0, 0);
                break;
            case R.id.flEqpList:
                if (FreeApi_StringUtils.isEmpty(location)) {
                    showToast("请选择区域", false);
                    return;
                }

                if (subEquipmentId.size() <= 0){
                    showToast("未获取到机台列表", false);
                    return;
                }
                if (EqpPop != null) {
                    if (EqpPop.isShowing()) {
                        EqpPop.dismiss();
                    }
                } else {
                    EqpPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flEqpList.getWidth(), subEquipmentId, ivEqpListArrow, (code, i) -> {
                        tvEqp.setText(code);
                        searchItemDevices(code);
                        tvSpareName.setText("");
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivEqpListArrow);
                EqpPop.showAsDropDown(flEqpList, 0, 0);
                break;
            case R.id.flReasonList:
                if (reasonList.size() <= 0) {
                    showToast("未获取到原因列表", false);
                    return;
                }

                if (reasonPop != null) {
                    if (reasonPop.isShowing()) {
                        reasonPop.dismiss();
                    }
                } else {
                    reasonPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flReasonList.getWidth(), reasonList, ivReasonListArrow, (code, i) -> {
                        tvReason.setText(code);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivReasonListArrow);
                reasonPop.showAsDropDown(flReasonList, 0, 0);
                break;
            case R.id.tvReplay:

                initPermission("Submit", this, new ActionControlListener() {
                    @Override
                    public void onControlChangeListener() {
                        submit();
                    }
                });

                break;
        }
    }

    /**
     * 根据主设备获取备件名称
     * @param mainWork
     */
    private void searchItemDevices(String mainWork) {
        if (FreeApi_StringUtils.isEmpty(mainWork)) {
            return;
        }
        JsonObject map = new JsonObject();
        map.addProperty("actionType", "onlySubEqp");
        map.addProperty("mainEquipmentId", mainWork);

        NetUtils.requestDara("HIK.PdaGetSubEqp", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<ItemWorkBean>>
                (new TypeToken<BaseResponseBean<ItemWorkBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<ItemWorkBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    subEquipmentId1 = response.body().getBody().getSubEquipmentId();
                    flSpareNameList.setEnabled(true);
                }else {
                    flSpareNameList.setEnabled(false);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<ItemWorkBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaGetSubEqp");

            }
        });
    }

    /**
     * 根据区域获取主设备
     * @param location
     */
    private void requestSubEqpList(String location) {
        JsonObject map = new JsonObject();
        map.addProperty("actionType", "getEqps");
        map.addProperty("area", location);

        NetUtils.requestDara("HIK.PdaGetSubEqp", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<ItemWorkBean>>
                (new TypeToken<BaseResponseBean<ItemWorkBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<ItemWorkBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    subEquipmentId = response.body().getBody().getSubEquipmentId();
                    flEqpList.setEnabled(true);
                }else {
                    flEqpList.setEnabled(false);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<ItemWorkBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaGetSubEqp");

            }
        });
    }

    private void submit() {
        String platFrom = tvEqp.getText().toString().trim();
        String reason = tvReason.getText().toString().trim().split("/")[0];
        String remarks = etRemarks.getText().toString().trim();
        String spareName = tvSpareName.getText().toString().trim();
        if (FreeApi_StringUtils.isEmpty(location)) {
            showToast("请选择区域", false);
            return;
        }

        if (FreeApi_StringUtils.isEmpty(platFrom)) {
            showToast("请选择机台", false);
            return;
        }

        if (FreeApi_StringUtils.isEmpty(reason)) {
            showToast("原因不能为空", false);
            return;
        }

        if (FreeApi_StringUtils.isEmpty(spareName)) {
            showToast("备件名称不能为空", false);
            return;
        }

        if (isFirst) {
            DialogUtils.showLoginDialog(this, userID -> {
                JsonObject map = new JsonObject();
                ReplaceRecordBean replaceRecordBean = new ReplaceRecordBean(location, platFrom, spareName, reason, remarks);
                map.addProperty("actionType", "save");
                map.addProperty("formType", "YSPJ");
                map.add("xPdaFormYiSunPeiJian", new JsonParser().parse(new Gson().toJson(replaceRecordBean)).getAsJsonObject());
                NetUtils.requestDara("HIK.PdaForm", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<?>>
                        (new TypeToken<BaseResponseBean<?>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<?>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                            showConfirmDialog(From_ReplaceRecordActivity.this, "提交成功");
                            isFirst = false;
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<?>> response) {
                        super.onError(response);
                        loadError(response.getException(), "HIK.PdaForm");
                    }
                });
            }, getSupportFragmentManager());
        } else {
            DialogUtils.showLoginDialog(this, Constant.CURRENT_USER, () -> {
                showConfirmDialog("操作人确认成功");
                tvReplay.setText("确认人确认");
                isFirst = true;
            }, getSupportFragmentManager());
        }


    }


}
